package com.itheima.immediate;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class MyRunnable implements Runnable{
    private Socket socket;
    private List<Socket> onlineSocket;
    public MyRunnable(Socket socket, List<Socket> onlineSocket){
        this.socket = socket;
        this.onlineSocket = onlineSocket;
    }
    @Override
    public void run() {
        // 获得输入流
        try {
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            // 读
            String msg;
            while ((msg = reader.readLine())!=null) {
                System.out.println(msg);
                //把这个消息转发给所有的管道； 输出流
                sendMsgToAll(msg);
            }
        } catch (Exception e) {  //出现异常；反正就是管道没了
            onlineSocket.remove(socket);
        }
    }
    public void sendMsgToAll(String msg){
        try {
            for (Socket socket1 : onlineSocket) {
                OutputStream outputStream = socket1.getOutputStream();
                PrintStream printStream = new PrintStream(outputStream);
                printStream.println(msg);
                printStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
